<template>
  <div
    class="container"
    :style="{ width: width + 'px', height: height + 'px' }"
  >
    <!-- 画板 -->
    <div
      id="zwibbler"
      :style="{ width: width + 'px', height: height + 'px' }"
    ></div>
    <!-- 画笔工具 -->
    <div class="tools-box">
      <!-- 矩形 -->
      <img
        id="rectangle"
        v-for="(item, index) in toolMaps"
        :key="index"
        @click="initTools(index)"
        class="tool-img"
        :class="index === 0 ? '' : 'mt20'"
        :src="chosedIndex === index ? item.chosed : item.unChosed"
      />
      <!-- 撤销单独列出 -->
      <img
        ref="undo"
        id="rectangle"
        @mousedown="unDoUp"
        @mouseup="unDo"
        class="tool-img mt20"
        src="//image.zlketang.com/public/news/images/home/revoke.png"
      />
    </div>
    <!-- 颜色和大小工具 -->
    <div
      v-if="chosedIndex !== -1 && chosedIndex !== 2 && chosedIndex !== 5"
      class="tools-color-box"
    >
      <!-- 粗细选择 -->
      <div class="tool-img" v-for="(item, index) in toolsFontSize" :key="index">
        <div
          @click="changeFintSize(index)"
          :style="{
            margin: 'auto',
            background:
              toolsFontSizeIndex === index
                ? toolsColor[toolsColorIndex]
                : '#999999',
            borderRadius: toolsFontSize[index] / 2 + 'px',
            border: '1px solid white',
            height: toolsFontSize[index] + 'px',
            width: toolsFontSize[index] + 'px'
          }"
        ></div>
      </div>
      <!-- 颜色选择 -->
      <div
        class="color-box"
        :style="{ 'background-color': toolsColor[index] }"
        :class="[
          index === 0 ? '' : 'mt20',
          index === toolsColorIndex ? 'border-blue' : ''
        ]"
        v-for="(item, index) in toolsColor"
        :key="index"
        @click="chosedColor(index)"
      ></div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'playList',
  props: {
    notesId: {
      type: Number,
      default: -1
    },
    width: {
      type: Number,
      default: 740
    },
    height: {
      type: Number,
      default: 414
    }
  },
  data() {
    return {
      // 画板对象
      ctx: null,
      // 选中的工具
      chosedIndex: -1,
      // 工具map
      toolMaps: [
        {
          chosed:
            '//image.zlketang.com/public/news/images/home/rectangle_chosed.png',
          unChosed: '//image.zlketang.com/public/news/images/home/rectangle.png'
        }, //矩形
        {
          chosed:
            '//image.zlketang.com/public/news/images/home/circular_chosed.png',
          unChosed: '//image.zlketang.com/public/news/images/home/circular.png'
        }, //圆形
        {
          chosed:
            '//image.zlketang.com/public/news/images/home/arrow_chosed.png',
          unChosed: '//image.zlketang.com/public/news/images/home/arrow.png'
        }, //箭头
        {
          chosed:
            '//image.zlketang.com/public/news/images/home/painting_chosed.png',
          unChosed: '//image.zlketang.com/public/news/images/home/painting.png'
        }, //画笔
        {
          chosed:
            '//image.zlketang.com/public/news/images/home/writing_chosed.png',
          unChosed: '//image.zlketang.com/public/news/images/home/writing.png'
        }, //文字
        {
          chosed:
            '//image.zlketang.com/public/news/images/home/eraser_chosed.png',
          unChosed: '//image.zlketang.com/public/news/images/home/eraser.png'
        } //橡皮擦
        // {
        //   chosed: '//image.zlketang.com/public/news/images/home/revoke_chosed.png',
        //   unChosed: '//image.zlketang.com/public/news/images/home/revoke.png'
        // } //撤销
      ],
      // 粗细选择 默认中等大小
      toolsFontSizeIndex: 1,
      // 文字大小设置
      toolsFontSize: [12, 14, 16],
      // 线条粗细设置
      lineWidth: [2, 4, 10],
      // 颜色选择 默认红色
      toolsColorIndex: 0,
      // 颜色设置
      toolsColor: ['red', 'yellow', 'blue', 'black', 'white'],
      uploadResult: null //图片上传后返回的地址
    }
  },
  methods: {
    init() {
      // 截图
      let player = document.getElementById('playerCont_html5_api') //获取video的Dom节点
      player.setAttribute('crossOrigin', 'anonymous') //添加srossOrigin属性，解决跨域问题
      let canvas = document.createElement('canvas')
      canvas.width = this.width
      canvas.height = this.height
      // let node = player
      canvas.globalAlpha = 1
      canvas.getContext('2d').drawImage(player, 0, 0, this.width, this.height) //截
      let dataURL = canvas.toDataURL('image/png') //将图片转成base64格式
      // 放入画板
      // eslint-disable-next-line no-undef
      this.ctx = Zwibbler.create('#zwibbler', {
        showToolbar: false, //是否显示默认工具栏
        showColourPanel: false, //是否显示颜色修改器
        showHints: false, //左上角是否显示提示
        // allowCrop: false,
        allowSelectBox: false, //是否允许选择框设置
        allowResize: false, //是否允许改变大小
        allowScroll: false, //是否允许滚动
        allowZoom: false, //是否允许缩放
        autoPickTool: false, // false 允许用户在绘制形状后绘制相同类型的形状 true 不允许用户在绘制形状后绘制相同类型的形状。
        backgroundImage: dataURL, //将截图作为背景图
        minAutoZoomTextSize: 0 //用于文本输入的时候 如果文本字体比较小 会有个放大的动作 这个属性是放大的时间
        // readOnly:true,//只读设置
        // selectMode:'surround',//surround 形状必须完全封闭在要选择的选定区域中 surround 与选定区域重叠的所有形状都将被选中。
      })
      this.ctx.usePickTool()
    },
    // 点击切换工具
    initTools(val) {
      this.chosedIndex = val !== this.chosedIndex ? val : -1
      this.changeTools(this.chosedIndex)
    },
    changeTools(val) {
      switch (val) {
        // 矩形
        case 0:
          this.ctx.useRectangleTool({
            fillStyle: 'rgba(0,0,0,0)',
            strokeStyle: this.toolsColor[this.toolsColorIndex],
            lineWidth: this.lineWidth[this.toolsFontSizeIndex]
          })
          break
        // 圆形
        case 1:
          this.ctx.useCircleTool({
            fillStyle: 'rgba(0,0,0,0)',
            strokeStyle: this.toolsColor[this.toolsColorIndex],
            lineWidth: this.lineWidth[this.toolsFontSizeIndex]
          })
          break
        // 箭头
        case 2:
          this.ctx.useArrowTool({
            arrowStyle: 'solid',
            strokeStyle: 'black',
            doubleArrow: false
          })
          break
        // 画笔
        case 3:
          this.ctx.useBrushTool({
            // lineWidth: 5, // optional
            lineWidth: this.lineWidth[this.toolsFontSizeIndex],
            strokeStyle: this.toolsColor[this.toolsColorIndex],
            fontSize: '12px'
          })
          break
        // 文字
        case 4:
          this.ctx.useTextTool({
            fontSize: this.toolsFontSize[this.toolsFontSizeIndex],
            textFillStyle: this.toolsColor[this.toolsColorIndex]
          })
          break
        // 橡皮
        case 5:
          this.ctx.useBrushTool({
            // lineWidth: this.toolsFontSize[this.toolsFontSizeIndex],
            strokeStyle: 'erase',
            layer: 'my_eraser_layer'
          })
          break
        // case 6:
        //   this.ctx.undo()
        //   break
        default:
          this.ctx.usePickTool()
          break
      }
    },
    unDoUp() {
      this.$refs.undo.src =
        '//image.zlketang.com/public/news/images/home/revoke_chosed.png'
    },
    unDo() {
      this.$refs.undo.src =
        '//image.zlketang.com/public/news/images/home/revoke.png'
      this.ctx.undo()
    },
    // 下载截图
    downloadImg() {
      let name = this.getImgName()
      this.ctx.download(name, { format: 'png' })
    },
    // 截图名 年月日时分
    getImgName() {
      const y = new Date().getFullYear()
      let m = new Date().getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = new Date().getDate()
      d = d < 10 ? '0' + d : d
      let h = new Date().getHours()
      h = h < 10 ? '0' + h : h
      let minute = new Date().getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      // let second = new Date().getSeconds();
      // second = second < 10 ? ('0' + second) : second;
      return y + '_' + m + '_' + d + '_' + h + '_' + minute
    },
    // 导出方法 导出格式是base64
    async save() {
      // 上传图片
      await this.getUploadResult()
      // 上传笔记
      this.$emit('uploadNotes', this.uploadResult)
    },
    // 上传图片 获取图片地址
    async getUploadResult() {
      let str = this.ctx.save({
        format: 'image/png'
      })
      // 将base64导出为file类型
      let file = this.base64ToFile(str)
      // 图片上传返回地址
      try {
        this.uploadResult = await this.uploadImg(file)
      } catch (error) {
        this.$message({ type: 'warning', message: '上传失败，请重试~' })
      }
    },
    // 笔记截图
    async notesSave() {
      // 上传图片
      await this.getUploadResult()
      // 插入笔记
      this.$bus.$emit('screenShotInjectNotes', this.uploadResult, this.notesId)
    },
    // base64转file
    base64ToFile(str) {
      let name = this.getImgName()
      let arr = str.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      let file = new File([u8arr], name, {
        type: mime
      })
      return file
    },
    // 上传文件
    async uploadImg(file) {
      let formData = new FormData()
      formData.append('from', 'web')
      formData.append('images', file)
      let res = await this.ajaxUpload('/wxpub/solution/upload_img', formData)
      return res.url || ''
    },
    // 改变字号
    changeFintSize(val) {
      this.toolsFontSizeIndex = val
      this.changeTools(this.chosedIndex)
    },
    // 选择颜色
    chosedColor(index) {
      this.toolsColorIndex = index
      this.changeTools(this.chosedIndex)
    }
  },
  watch: {},
  mounted() {
    this.init()
  }
}
</script>
<style scoped>
.container {
  /* width: 740px;
  height: 414px; */
  margin: auto;
  border-radius: 12px;
  /* overflow: hidden; */
  position: relative;
}
#zwibbler {
  /* width: 740px;
  height: 414px; */
  border-radius: 12px;
  overflow: hidden;
}
.tools-box {
  position: absolute;
  right: -62px;
  top: 0;
  padding: 16px 10px;
  background: rgba(0, 0, 0, 0.5);
}
.tool-img {
  display: block;
  width: 24px;
  height: 24px;
  cursor: pointer;
}
.tools-color-box {
  position: absolute;
  right: -104px;
  top: 0;
  padding: 16px 10px;
  background: rgba(0, 0, 0, 0.5);
}
.color-box {
  width: 24px;
  height: 24px;
  cursor: pointer;
  border-radius: 2px;
  border: 1px solid white;
}
.border-blue {
  border-color: blue;
}
</style>
